package com.cn.wkditui;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.cn.wkditui.bean.QBean;



/**
 * Created by wyd on 2016/3/15.
 */
public class QAQActivity  extends  BaseActivity{

    private MyListView lv ;
    private List<QBean> beans;
    private Button bt,bt_no,btBefore;
    //    private List<String> l2= new ArrayList<>();
//    private Map<String ,List<String> list> mutiList = new ArrayList<>();
    private QBean  q1,q2,q3,q4,q5,q6,q7,q8,q9,q10,q11;

    private boolean isEdit;

    private Map<String,List> mutiList = new HashMap<>();
    private int[] imgs = new int[]{
            R.mipmap.i1,
            R.mipmap.i2,
            R.mipmap.i3,
            R.mipmap.i4,
            R.mipmap.i5,
            R.mipmap.i6,
            R.mipmap.i7,
            R.mipmap.i8,
            R.mipmap.i9,
            R.mipmap.i10,
    };
    private String[] name = new String[]{
            "价格",
            "物流",
            "便捷",
            "产品丰富",
            "资金安全",
            "调换货保障",
            "产品质量",
            "平台简洁",
    };
    private List<Float> ra = new ArrayList<>();
    private MyListView lv2;
    private List<String> noAnswer = new ArrayList<>();
    private String id ="";

    private EditText et ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qaq);
        init();
        setDate();
        if(isEdit){
            load();
        }else{

        }
        btBefore= (Button) findViewById(R.id.bt_before);
        bt_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO: 2016/4/21 不配合

                Utils.ShowDialog(QAQActivity.this, Consts.TITLE, new Utils.CallBack() {
                    @Override
                    public void onclickConfirm(Dialog dialog) {
                        noRegister(dialog);
                    }

                    @Override
                    public void onclickCancel(Dialog dialog) {
                        dialog.dismiss();
                    }
                });
            }
        });
        btBefore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(QAQActivity.this, Auth1Activity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.putExtra("id", id);
                startActivity(intent);
            }
        });


        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                noAnswer.clear();

                JSONObject j = new JSONObject();
                for (int i = 0; i < beans.size(); i++) {
                    try {


                        if (beans.get(i).isSingle()) {
                            if (beans.get(i).getAnswer() == null) {
                                noAnswer.add((i + 1) + "");
                            } else {

                                j.put(i + 1 + "", beans.get(i).getAnswer());
                            }
                        } else {
                            noAnswer.add((i + 1) + "");
                            //多选
                            Integer re = 0;
                            //没有多选
                            Log.e("", "多选======" + mutiList.size());
                            Log.e("w", "多选(i+1)" + (i) + "是否包含"
                                    + mutiList
                                    .containsKey((i) + ""));
//                                for(int i1=0;i1<mutiList.size();i1++){
                            if (mutiList.containsKey(i + "")) {
                                Log.e("caon", "是否为空====="
                                        + mutiList.get(i + "").size());
                                if (mutiList.get(i + "").size() == 0) {

                                } else {
                                    noAnswer.remove((i + 1) + "");
                                    JSONArray j2 = new JSONArray();
                                    for (int c = 0; c < mutiList.get(i + "").size(); c++) {

                                        j2.put(c, mutiList.get(i + "").get(c));
                                        Log.e("撒啊", "把" + mutiList.get(i + "").get(c) + "放入第" + (i + 1) + "题");
                                    }
                                    j.put((i + 1) + "", j2);
                                }
                            }
                        }

//                        if (i == 1) {
//                            Log.e("l2", "l2的长度" + l2.size());
//                            if (l2.size() == 0) {
//                                noAnswer.add(2);
//                            } else {
//
//                                for (int c = 0; c < l2.size(); c++) {
//
//                                    j2.put(c, l2.get(c));
//                                }
//                            }
//
//                        }
//                        JSONObject json  = new JSONObject();
//                        if (i == 1) {
//                            j.put("2", j2);
//                        } else {
//                            if (beans.get(i).getAnswer() == null) {
//                                noAnswer.add(i + 1);
//                            } else {
//
//                                j.put(i + 1 + "", beans.get(i).getAnswer());
//                            }
//
//                        }

//                        j.putOpt("Answer",json);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

                JSONArray array = new JSONArray();
                for (int x = 0; x < ra.size(); x++) {
                    try {
                        if (ra.get(x) == -1) {
                            if (!noAnswer.contains("11")) {

                                noAnswer.add(11 + "");
                            }
                        }
                        array.put(x, ra.get(x));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    j.put("11", array);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (noAnswer.size() == 0) {
                    //TODO

                    Log.e("result", "result=-=======" + j);
                    commit(j);

                } else {
                    String s = "";
                    for (int i = 0; i < noAnswer.size(); i++) {
                        if (i == 0) {
                            s += noAnswer.get(i);
                        } else {
                            s += ("," + noAnswer.get(i));
                        }
                    }
                    Toast.makeText(QAQActivity.this, "您第" + s + "题没有回答", 0).show();
                    noAnswer.clear();

                }
                Log.e("", "点击了=================j" + j);

                System.out.print("点击了====================");
            }
        });

    }

    private void noRegister(final Dialog dialog) {
        RequestParams param = new RequestParams();
        Log.e("id", "id===========" + id);
        param.addBodyParameter("staffPhone", MyPreference.getInstance(QAQActivity.this).getStaffid());
        param.addBodyParameter("id",id);
        param.addBodyParameter("questionComment",et.getText().toString());

        param.addBodyParameter("status","-1");
        new HttpUtils().send(HttpRequest.HttpMethod.POST, Consts.HOST + Consts.ADDSUVER, param, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                dialog.dismiss();
                Log.e("qaq",responseInfo.result);
                try {
                    JSONObject json = new JSONObject(responseInfo.result);
                    if(json.getInt("code")==1){
                        Intent intent = new Intent(QAQActivity.this,MainActivity.class);
                        if(isEdit){
                            intent.putExtra("act","edit");
                        }
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {
                dialog.dismiss();
                Toast.makeText(QAQActivity.this,"网络异常",0).show();
            }
        });
    }

    private void setDate() {
        for(int i=0;i<name.length;i++){
            ra.add(-1f);
        }
        lv2.setAdapter(new RaAadapter(ra));
        Log.e("QAQ","新的");
         q1= new QBean("商铺/公司所在区域",true,3,"学校","社区","CBD");
          q2= new QBean("经营类别(多选)",false,4,"办公文体","日用百货","玩具","超市");
          q3= new QBean("经营年限",true,4,"2年以下","3-5年","6-10年","10年以上");
          q4= new QBean("经营面积",true,4,"30平以下","30-50平","50-80平","80平以上");
          q5= new QBean("人员规模(含经营者)",true,4,"1-2人","3-5人","6-10人","10人以上");
          q6= new QBean("经营者年龄",true,4,"25岁以下","25-35岁","35-45岁","45岁以上");
          q7= new QBean("商铺(公司)的年营业收入大致为多少万元",true,4,"10万以下","10-30万","30-50万","50万以上");
          q8= new QBean("进货周期",true,4,"3天以下","3-7天","7-15天","15天以上");
          q9= new QBean("单次进货额",true,4,"500元以下","500-1000元","1000-3000元","3000元以上");
          q10= new QBean("网络购物经验",false,3,"手机APP购物","电脑端购物","无网络购物经验");
        beans.add(q1);
        beans.add(q2);
        beans.add(q3);
        beans.add(q4);
        beans.add(q5);
        beans.add(q6);
        beans.add(q7);
        beans.add(q8);
        beans.add(q9);
        beans.add(q10);
        lv.setAdapter(new LvAdapter(beans));
    }

    private void load() {
        RequestParams param = new RequestParams();
        Log.e("QAQ","id====="+id);
        param.addBodyParameter("id",id);
        new HttpUtils().send(HttpRequest.HttpMethod.POST, Consts.HOST + Consts.GETSURVER, param, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("Load", responseInfo.result);
                try {
//                    ra.clear();
                    JSONObject json = new JSONObject(responseInfo.result);
                    if (json.getInt("code") == 1) {
                        if(!json.getJSONObject("data").getString("question1").equals("")){

                        q1.setAnswer(json.getJSONObject("data").getString("question1"));
                        q2.setAnswer(json.getJSONObject("data").getString("question2"));
                        q3.setAnswer(json.getJSONObject("data").getString("question3"));
                        q4.setAnswer(json.getJSONObject("data").getString("question4"));
                        q5.setAnswer(json.getJSONObject("data").getString("question5"));
                        q6.setAnswer(json.getJSONObject("data").getString("question6"));
                        q7.setAnswer(json.getJSONObject("data").getString("question7"));
                        q8.setAnswer(json.getJSONObject("data").getString("question8"));
                        q9.setAnswer(json.getJSONObject("data").getString("question9"));
                        q10.setAnswer(json.getJSONObject("data").getString("question10"));
//                        q11.setAnswer(json.getJSONObject("data").getString("question11"));
//                        for(int i=0;i<name.length;i++){
//                            ra.add(-1f);
//
//                        }
                        List<Integer> l = new ArrayList<Integer>();
                        l.add(2);
                        l.add(10);
                            //题号 ，但是内部方法 0开始
                        setMulti(json, l);
                            String[] ss = json.getJSONObject("data").getString("question11").split(",");
                            for(int i=0;i<ss.length;i++){
                                ra.set(i,Float.parseFloat(ss[i]));
                            }

//                        for (String s : json.getJSONObject("data").getString("question11").split(",")) {
//                            ra.set( Float.parseFloat(s));
//                            Log.e("QAQ","s====="+s);
//                        }


                        lv.setAdapter(new LvAdapter(beans));
                        lv2.setAdapter(new RaAadapter(ra));
                        }
                    } else {
                        Toast.makeText(QAQActivity.this, json.getString("message"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();

                }


            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });
    }

    private void setMulti(JSONObject json,List<Integer> l) throws JSONException {
        Log.e("", "增加的" + json.getJSONObject("data").getString(("question" + 2)).split(","));
        ArrayList<String> a ;
        for(int i :l){
            a = new ArrayList<String>();
            for(String s : json.getJSONObject("data").getString(("question" + i)).split(",")){
                Log.e("","增加的"+s);
                a.add(s);
            }
            mutiList.put(""+(i-1),a);
        }
        Log.e("","mutiList======"+mutiList.size());
    }

    private void commit(JSONObject j) {
        RequestParams param = new RequestParams();
        param.addBodyParameter("id",id);
        param.addBodyParameter("survey", j.toString());
        param.addBodyParameter("staffPhone", MyPreference.getInstance(this).getStaffid());
        param.addBodyParameter("questionComment", et.getText().toString());
        Log.e("id", "id=====" + id);
        Log.e("surveyId", "staffPhone=====" + MyPreference.getInstance(this).getStaffid());
        Log.e("survey", "survey=====" + j.toString());
        new HttpUtils().send(HttpRequest.HttpMethod.POST, Consts.HOST + Consts.ADDSUVER, param, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                try {
                    JSONObject json = new JSONObject( responseInfo.result);
                    if(json.getInt("code")==1){
                        Intent intent = new Intent(QAQActivity.this,Auth2Activity.class);
                        if(isEdit){
                            intent.putExtra("act", "edit");
                        }
                        intent.putExtra("id", id);
                        Log.e("QAQ", "传个下ID" + id);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                    }else{
                        Toast.makeText(QAQActivity.this, json.getString("message"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();

                }


            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });
    }

    private void init() {
        et = (EditText) findViewById(R.id.et_commet);
        ImageView iv2 = (ImageView) findViewById(R.id.iv2);
        iv2.requestFocus();
        iv2.setFocusable(true);
        lv = (MyListView) findViewById(R.id.lv);
        lv2 = (MyListView) findViewById(R.id.lv2);
        bt= (Button) findViewById(R.id.btcommit);
        btBefore= (Button) findViewById(R.id.bt_before);
        bt_no= (Button) findViewById(R.id.bt_no);
        ScrollView sc =(ScrollView)findViewById(R.id.sc);
        sc.smoothScrollTo(0, 20);
        beans = new ArrayList<>();
        id= getIntent().getStringExtra("id");

        if(getIntent().hasExtra("act")){
            isEdit =true;
        }else{
            isEdit =false;
        }

        Log.e("Auth2","是否编辑:"+isEdit);

    }



    class LvAdapter extends BaseAdapter{

        private final List<QBean> b;
        private int selection = -1;
        public LvAdapter(List<QBean> beans) {
            this.b = beans;
        }

        @Override
        public int getCount() {
            return b.size();
        }

        @Override
        public Object getItem(int i) {
            return b.get(i);
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(final int i, View view, ViewGroup viewGroup) {
            view = View.inflate(QAQActivity.this,R.layout.lv_qaq,null);
            final CheckBox ck1 = (CheckBox) view.findViewById(R.id.ck1);
            final CheckBox ck2 = (CheckBox) view.findViewById(R.id.ck2);
            final CheckBox ck3 = (CheckBox) view.findViewById(R.id.ck3);
            final CheckBox ck4 = (CheckBox) view.findViewById(R.id.ck4);

            TextView tv = (TextView) view.findViewById(R.id.tv);
            ImageView iv = (ImageView) view.findViewById(R.id.iv);
            //有答案
            Log.e("getVIew",""+(b.get(i).getAnswer()!=null));
            if(b.get(i).getAnswer()!=null){
                if( b.get(i).getAnswer().contains(",")){
                    //多选的
                    String[] s = b.get(i).getAnswer().split(",");
                    for(String sa : s){
//                        l2.add(sa);
                        switch (sa){
                            case "1":
                                ck1.setChecked(true);
                                break;
                            case "2":
                                ck2.setChecked(true);
                                break;
                            case "3":
                                ck3.setChecked(true);
                                break;
                            case "4":
                                ck4.setChecked(true);
                                break;
                        }
                    }
//                    if(mutiList.containsKey(i+"")){
//                        Log.e("getView","多选====没有======");
//                    }else{
//                        Log.e("getView","多选====放入======");
//                        mutiList.put(i + "", l2);
//                    }


                }else{
                    //单选
                    switch (b.get(i).getAnswer()){
                        case "1":
                            ck1.setChecked(true);
                            break;
                        case "2":
                            ck2.setChecked(true);
                            break;
                        case "3":
                            ck3.setChecked(true);
                            break;
                        case "4":
                            ck4.setChecked(true);
                            break;
                    }
                }
            }


            ck1.setText(b.get(i).getA1());
            ck2.setText(b.get(i).getA2());
            ck3.setText(b.get(i).getA3());
            if(b.get(i).getCount()==3){
                ck4.setVisibility(View.INVISIBLE);
            }else{
                ck4.setVisibility(View.VISIBLE);
                ck4.setText(b.get(i).getA4());

            }
            if(b.get(i).isSingle()){
                ck1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean bo) {
                        if (bo) {
                            ck2.setChecked(false);
                            ck3.setChecked(false);
                            ck4.setChecked(false);
                            b.get(i).setAnswer("1");
                        }
                    }
                });
                ck2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean bo) {
                        if (bo) {
                            ck1.setChecked(false);
                            ck3.setChecked(false);
                            ck4.setChecked(false);
                            b.get(i).setAnswer("2");
                        }
                    }
                });
                ck3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean bo) {
                        if (bo) {
                            ck2.setChecked(false);
                            ck1.setChecked(false);
                            ck4.setChecked(false);
                            b.get(i).setAnswer("3");
                        }
                    }
                });
                ck4.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean bo) {
                        if (bo) {
                            ck2.setChecked(false);
                            ck1.setChecked(false);
                            ck3.setChecked(false);
                            b.get(i).setAnswer("4");
                        }
                    }
                });

            }else{
                final List<String> l2;
                if(mutiList!=null&&mutiList.size()!=0&&mutiList.containsKey(""+i)){

                    l2 = mutiList.get(i+"");
                }else{
                    l2 = new ArrayList<>();
                }
                Log.e("","多选======="+b.get(i).getName()+"=====i========================"+i);
                ck1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean bo) {
                        if (bo) {
                            if(!l2.contains("1")){
                                l2.add(1+"");
                            }
                        }else{
                            l2.remove("1");
                        }
                        mutiList.put(i+"",l2);
                    }
                });
                ck2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean bo) {
//                        Log.e("getVIew","长度"+mutiList.size());
                        if (bo) {
                            if(!l2.contains("2")){
                                l2.add(2 + "");
                            }
                        }else{
                            l2.remove("2");
                        }
                        mutiList.put(i+"",l2);
                    }
                });
                ck3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean bo) {
                        if (bo) {
                            if (!l2.contains("3")) {
                                l2.add(3 + "");
                            }
                        } else {
                            l2.remove("3");
                        }
                        mutiList.put(i + "", l2);
                    }
                });
                ck4.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean bo) {

                        if (bo) {
                            if (!l2.contains("4")) {
                                l2.add(4 + "");
                            }
                        } else {
                            l2.remove("4");
                        }
                        mutiList.put(i + "", l2);
                    }
                });
            }
//            mutiList.add(l2);
            iv.setImageResource(imgs[i]);
            tv.setText(b.get(i).getName());

            return view;
        }

        private void setSelection(int position){
            this.selection = position;
        }
        private int getSelection(){
            return  selection;
        }
    }


    class RaAadapter extends  BaseAdapter{


        private final List<Float> b;

        public RaAadapter(List<Float> b){
            this.b = b;
        }


        @Override
        public int getCount() {
            return b.size();
        }

        @Override
        public Object getItem(int i) {
            return b.get(i);
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(final int i, View view, ViewGroup viewGroup) {
            view =View.inflate(QAQActivity.this, R.layout.lv_qaq_rating, null);
            RatingBar rb = (RatingBar) view .findViewById(R.id.rb);
//            if(getIntent().hasExtra("path")){
//                rb.setRating(b.get(i));
//            }
            if(isEdit){
                rb.setRating(b.get(i));
            }



            TextView tv = (TextView) view .findViewById(R.id.tv);
            tv.setText(name[i]);
            rb.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
                @Override
                public void onRatingChanged(RatingBar ratingBar, float v, boolean bo) {
                    b.set(i,v);
                }
            });

            return view;
        }
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return  true;
    }
}
